<template>
  <el-dialog title="新增用户" width="40%" v-model="dialogVisible" @close="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false">
    <!--form表单-->
    <el-card style="margin-top:-10px;">
      <el-form size="small" ref="form" :model="form" :rules="formRules" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="form.realName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属角色" prop="role">
              <el-select clearable v-model="form.role" style="width:100%;">
                <el-option v-for="item in roleList" :value="item.roleId" :key="item.roleId" :label="item.roleName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="userGroup">
              <el-select clearable v-model="form.userGroup" :multiple="false" style="width:100%;">
                <el-option v-for="item in interDeparts" :value="item.value" :key="item.value" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="personGender">
              <el-radio-group v-model="form.userGender">
                <el-radio :label="1" border>男</el-radio>
                <el-radio :label="2" border>女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话/手机号" prop="userMobile">
              <el-input v-model="form.userMobile" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="城市" prop="areaIds" v-if="form.userGroup === 5" :rules="[{ required: true, message: '请选择城市', trigger: 'change' }]">
          <el-checkbox-group v-model="form.areaIds">
            <el-checkbox v-for="(item, index) in checkBoxOptions" :key="index" :label="item.appid">
              {{ item.areaName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="头像" v-if="form.userGroup === 5">
          <div style="width: 60px; height: 60px" v-show="form.personAvatarImg">
            <img :src="form.personAvatarImg" style="width: 100%; height: 100%">
          </div>
          <el-button type="primary" style="margin: 5px;" size="small" @click="openImage">选择图片</el-button>
        </el-form-item>

        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入登录密码" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" placeholder="请输入确认密码" type="password"></el-input>
        </el-form-item>
        <el-form-item label="是否可用" prop="disabled">
          <el-switch v-model="form.disabled" size="small" active-text="启用" inactive-text="禁用" :active-value="false" :inactive-value="true" />
        </el-form-item>
      </el-form>
    </el-card>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 上传 -->
  <Upload v-if="isProductUpload" :config="config" :isupload="isProductUpload" @returnImgs="returnProductImgsFunc">
    上传图片
  </Upload>
</template>

<script>
import AuthApi from "@/api/auth.js";
import { useCascaderAreaData } from '@/utils/area'
import SalesApi from '@/api/sales'
export default {
  data() {
    return {
      /*左边长度*/
      formLabelWidth: "120px",
      /*是否显示*/
      loading: false,
      /*是否显示*/
      defaultData: useCascaderAreaData(),
      dialogVisible: false,
      isProductUpload: false,
      /*form表单对象*/
      form: {
        userName: "",
        realName: '',
        userGroup: '',
        userAvatar: '',
        role: '',
        personAvatarImg: "",
        userMobile: '',
        userGender: '',
        areaIds: [],
        disabled: false,
        confirmPassword: '',
      },
      /*form验证*/
      formRules: {
        userName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        areaIds: [
          {
            required: true,
            message: "请选择城市",
          },
        ],
        realName: [
          {
            required: true,
            message: "请输入真实姓名",
            trigger: "blur",
          },
        ],
        roleId: [
          {
            required: true,
            message: "请选择角色",
            trigger: "blur",
          },
        ],
        userGroup: [
          {
            required: true,
            message: "请选择部门",
            trigger: "blur",
          }
        ],
        userMobile: [
          {
            required: true,
            message: "请输入电话/手机号",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入登录密码",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          {
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请确认您的密码'));
              } else if (value !== this.form.password) {
                callback(new Error('两次输入密码不一致!'));
              } else {
                callback();
              }
            }
          },
        ]
      },
      interDeparts: [
        { label: '生产部', value: 1 },
        { label: '仓库管理部', value: 2 },
        { label: '市场部', value: 3 },
        { label: '客服部', value: 4 },
        { label: '销售部', value: 5 },
        { label: '财务部', value: 6 },
        { label: '电商部', value: 7 },
        { label: '技术部', value: 8 },
        { label: '退款管理员', value: 9 }
      ],
      checkBoxOptions: []
    };
  },
  props: ["open", "roleList"],
  watch: {
    open: function (n, o) {
      if (n != o) {
        this.clearForm()
        this.dialogVisible = this.open;
      }
    },
  },
  created() {
    this.loadAreas()
  },
  methods: {

    loadAreas() {
      const $this = this
      SalesApi.getAreaList()
        .then(result => {
          const { code, data } = result
          if (code === 1) {
            console.log('data', data)
            data.forEach(item => {
              const json = {
                name: '',
                appid: item.areaId,
                areaName: item.areaName,
                areaCode: item.areaCode
              }
              json.name = $this.convertAreas(item)
              $this.checkBoxOptions.push(json)
            })
          }
        })

    },
    convertAreas(item) {
      const $this = this
      const provice = $this.defaultData.find(f => f.value === item.province)
      const areaValues = []
      if (provice) {
        areaValues.push(provice.label)
        if (provice.children && provice.children.length > 0) {
          const city = provice.children.find(f => f.value === item.city)
          if (city) {
            areaValues.push(city.label)
            if (city.children && city.children.length > 0) {
              const dis = city.children.find(f => f.value === item.district)
              if (dis) {
                areaValues.push(dis.label)
              }
            }
          }


        }
      }
      return areaValues.join('/')
    },
    openImage() {
      this.isProductUpload = true
    },
    returnProductImgsFunc(e) {
      if (e && e.length > 0) {
        this.imageInfo = {
          imageId: e[0].fileId,
          filePath: e[0].filePath
        }
        this.form.personAvatar = this.imageInfo.imageId
        this.form.userAvatar = this.imageInfo.imageId
        this.form.personAvatarImg = this.imageInfo.filePath
        this.isProductUpload = false
      }
    },
    clearForm() {
      const self = this
      self.form.password = ''
      self.form.confirmPassword = ''
      self.form.userAvatar = ''
      self.form.userName = ''
      self.form.userGroup = ''
      self.form.personAvatarImg = ''
      self.form.userMobile = ''
      self.form.userGender = 1
      self.form.areaIds = []
      self.form.role = ''
      self.form.disabled = false

    },
    /*添加*/
    onSubmit() {
      let self = this;
      let params = self.form;
      self.$refs['form'].validate((valid) => {
        if (valid) {
          self.loading = true;
          AuthApi.userAdd(params, true)
            .then((data) => {
              self.loading = false;
              ElMessage({
                message: "恭喜你，添加成功",
                type: "success",
              });
              self.clearForm()
              self.dialogFormVisible(true);
            })
            .catch((error) => {
              self.loading = false;
            });
        }
      })
    },
    /*关闭弹窗*/
    dialogFormVisible(e) {
      if (e) {
        this.$emit("close", {
          type: "success",
          openDialog: false,
        });
      } else {
        this.$emit("close", {
          type: "error",
          openDialog: false,
        });
      }
    },
  },
};
</script>

<style></style>
